package com.lineage.server.clientpackets;

import com.lineage.echo.ClientExecutor;
import com.lineage.server.datatables.CharObjidTable;
import com.lineage.server.datatables.lock.BuddyReading;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1BuddyTmp;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class C_AddBuddy extends ClientBasePacket {
  private static final Log _log = LogFactory.getLog(C_AddBuddy.class);
  
  public void start(byte[] decrypt, ClientExecutor client) {
    try {
      read(decrypt);
      String charName = readS().toLowerCase();
      L1PcInstance pc = client.getActiveChar();
      ArrayList<L1BuddyTmp> list = BuddyReading.get().userBuddy(pc.getId());
      if (list != null) {
        if (charName.equalsIgnoreCase(pc.getName()))
          return; 
        Iterator<L1BuddyTmp> iterator = list.iterator();
        while (iterator.hasNext()) {
          L1BuddyTmp buddyTmp = iterator.next();
          if (charName.equalsIgnoreCase(buddyTmp.get_buddy_name()))
            return; 
        } 
      } 
      int objid = CharObjidTable.get().charObjid(charName);
      if (objid != 0) {
        String name = CharObjidTable.get().isChar(objid);
        BuddyReading.get().addBuddy(pc.getId(), objid, name);
        return;
      } 
      pc.sendPackets((ServerBasePacket)new S_ServerMessage(109, charName));
    } catch (Exception exception) {
    
    } finally {
      over();
    } 
  }
  
  public String getType() {
    return getClass().getSimpleName();
  }
}
